<template>
  <AuthLayout>
    <el-card class="auth-card" shadow="never">
      <template v-slot:header>
        <div class="auth-card-header">
          <h2>用户注册</h2>
        </div>
      </template>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-position="top"
        @keyup.enter="handleRegister"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名 (3-16位字母/数字/下划线)"
            prefix-icon="User"
            size="large"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱地址"
            prefix-icon="Message"
            size="large"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码 (至少6位)"
            prefix-icon="Lock"
            show-password
            size="large"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            prefix-icon="Lock"
            show-password
            size="large"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="success"
            @click="handleRegister"
            :loading="loading"
            size="large"
            class="auth-button"
          >
            注 册
          </el-button>
        </el-form-item>
      </el-form>

      <div class="auth-footer">
        <p>已有账号？ <el-link type="primary" @click="$router.push('/login')" class="auth-link">立即登录</el-link></p>
      </div>

      <div v-if="successMessage" class="auth-success">
        {{ successMessage }}
      </div>

      <div v-if="errorMessage" class="auth-error">
        {{ errorMessage }}
      </div>
    </el-card>
  </AuthLayout>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { signup } from '@/services/authService'
import AuthLayout from '@/components/AuthLayout.vue'
import { User, Message, Lock } from '@element-plus/icons-vue'

const router = useRouter()

const registerFormRef = ref()
const loading = ref(false)
const successMessage = ref('')
const errorMessage = ref('')

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]{3,16}$/, message: '用户名只能包含字母、数字、下划线，长度3-16位', trigger: 'bl极' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      successMessage.value = ''
      errorMessage.value = ''
      try {
        const { username, email, password } = registerForm;
        await signup({ username, email, password });
        successMessage.value = '注册成功！即将跳转到登录页...';
        setTimeout(() => {
          router.push('/login');
        }, 2000);
      } catch (error) {
        console.error('Registration failed:', error);
        errorMessage.value = error.response?.data?.message || '注册失败。';
      } finally {
        loading.value = false;
      }
    } else {
      console.log('Form validation failed!');
      return false;
    }
  });
};
</script>

<style scoped>
.auth-card {
  border: none;
  background: transparent;
}

.auth-card-header {
  text-align: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #eee;
}

.auth-card-header h2 {
  margin: 0;
  font-size: 1.8rem;
  font-weight: 600;
  color: #4CAF50;
  position: relative;
  display: inline-block;
}

.auth-card-header h2:after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 3px;
  background: #4CAF50;
  border-radius: 3px;
}

.el-form-item {
  margin-bottom: 1.8rem;
}

.auth-button {
  width: 100%;
  border-radius: 8px;
  padding: 12px 20px;
  font-weight: 600;
  letter-spacing: 1px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(76, 175, 80, 0.3);
}

.auth-footer {
  text-align: center;
  margin-top: 1.5rem;
  font-size: 0.9rem;
  color: #666;
}

.auth-link {
  color: #4CAF50;
  font-weight: 600;
  text-decoration: none;
  transition: all 0.2s ease;
  position: relative;
}

.auth-link:hover {
  color: #8BC34A;
}

.auth-link:after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 1px;
  background: #4CAF50;
  transform: scaleX(0);
  transition: transform 0.2s ease;
}

.auth-link:hover:after {
  transform: scaleX(1);
}

.auth-success {
  margin-top: 1.5rem;
  padding: 1rem;
  background-color: rgba(76, 175, 80, 0.1);
  border: 1px solid rgba(76, 175, 80, 0.2);
  border-radius: 8px;
  color: #4CAF50;
  font-size: 0.9rem;
  text-align: center;
}

.auth-error {
  margin-top: 1.5rem;
  padding: 1rem;
  background-color: rgba(255, 0, 0, 0.05);
  border: 1px solid rgba(255, 0, 0, 0.1);
  border-radius: 8px;
  color: #f56c6c;
  font-size: 0.9rem;
  text-align: center;
}

/* Element Plus Button 样式微调 */
:deep(.el-button--success) {
  background: linear-gradient(135deg, #4CAF50 0%, #8BC34A 100%);
  border: none;
}

:deep(.el-button--success:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(76, 175, 80, 0.4);
}
</style>
